package com.example.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.example.reggie.common.MyBaseContext;
import com.example.reggie.common.R;
import com.example.reggie.entity.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
//import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName ="loginCheck",  urlPatterns = "/*")
public class LoginFilter implements Filter {
    public static final AntPathMatcher pathMatch = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg"
        };
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        boolean chk = check(urls, requestURI);
        if (chk) {
            log.info("不处理："+requestURI);
            filterChain.doFilter(request, response);
            return;
        }
            Long empId= (Long) request.getSession().getAttribute("employee");
            Long userId= (Long) request.getSession().getAttribute("user");

         if (empId == null&& userId==null) {
            log.info("处理"+requestURI);
            response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
            return;

        } else if(empId!=null&&userId!=null){
//            MyBaseContext.setEmpIdByThread(empId);
            log.info("有user和empId session不处理"+requestURI);
            filterChain.doFilter(request, response);
        }
         else if(empId!=null){
             MyBaseContext.setEmpIdByThread(empId);
             log.info("有emp session不处理"+requestURI);
            filterChain.doFilter(request, response);
         }else {
             MyBaseContext.setEmpIdByThread(userId);
             log.info("有user session不处理"+requestURI);
             filterChain.doFilter(request, response);
         }
    }



    public boolean check(String[] urls, String requesturl) {
        for (String url : urls) {
            if (pathMatch.match(url, requesturl)) {
                return true;
            }
        }
        return false;
    }
}
